package com.duowei.diandan.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.duowei.diandan.R;
import com.duowei.diandan.adapter.DeskCateAdapter;
import com.duowei.diandan.adapter.DeskItemAdapter;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.Desk;
import com.duowei.diandan.bean.DeskGroup;
import com.duowei.diandan.bean.DeskStatus;
import com.duowei.diandan.constant.NetConfig;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.databinding.DeskFragmentBinding;
import com.duowei.diandan.db.DeskList;
import com.duowei.diandan.db.entry.Dccz;
import com.duowei.diandan.db.entry.Gklx;
import com.duowei.diandan.db.entry.Jycssz;
import com.duowei.diandan.db.entry.Wmlsb;
import com.duowei.diandan.db.entry.Wmlsbjb;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.fragment.dialog.InputDialogFragment;
import com.duowei.diandan.fragment.dialog.MergeTableDialogFragment;
import com.duowei.diandan.fragment.dialog.OpenTableDialogFragment;
import com.duowei.diandan.fragment.dialog.PromptDialogFragment;
import com.duowei.diandan.sql.OrderCommit;
import com.duowei.diandan.util.NetUtils;

import org.greenrobot.eventbus.EventBus;
import org.joda.time.LocalDateTime;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DeskFragment extends BaseFragment implements DeskCateAdapter.OnCateItemClickListener, DeskItemAdapter.OnDeskItemClickListener {
    public static final String TAG = "DeskFragment";

    private DeskFragmentBinding mBinding;

    private DeskCateAdapter mCateAdapter;
    private DeskItemAdapter mItemAdapter;

    private Handler mHandler = new Handler();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_desk, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        List<DeskGroup> deskGroupList = DeskList.getInstance().getDeskGroupList();
        if (deskGroupList.size() == 0) {
            Toast.makeText(getContext(), "未发现餐桌列表", Toast.LENGTH_SHORT).show();

        } else {
            mCateAdapter = new DeskCateAdapter(deskGroupList, this);
            mBinding.cateRecyclerView.setAdapter(mCateAdapter);

            mItemAdapter = new DeskItemAdapter(DeskList.getInstance().getAllDeskList(), this);
            mBinding.deskRecyclerView.setAdapter(mItemAdapter);
            ((GridLayoutManager) mBinding.deskRecyclerView.getLayoutManager()).setSpanCount(Settings.COLUMN_DESK_CHOICE);
        }
    }

    @Override
    public void onStart() {
        super.onStart();

        getDb().dcczDao().deleteAll();
    }

    public void createDesk(Jycssz jycssz, Gklx gklx, int peopleNum) {
        OrderList.getInstance().createWmlsbjb(jycssz, gklx, peopleNum);

        new OrderCommit().createWmlsbjbOnSqlServer(new OrderCommit.OnStatusListener() {
            @Override
            public void onSuccess() {
                Log.i(TAG, "onSuccess: 创建订单成功");

                createDccz(jycssz.getCsbh() + ",");

                mOnGotoListener.onGotoMenuFragment();
            }

            @Override
            public void onFail() {
                EventBus.getDefault().post(new ToastEvent("创建订单失败", false));
            }
        });
    }

    private void queryServerOrder(DeskStatus deskStatus) {
        new Thread(() -> {
            try {
                List<Wmlsbjb> wmlsbjbList = NetUtils.post6(NetConfig.getServerUrl(),
                        Wmlsbjb.toQuerySql(deskStatus.getWmdbh()), Wmlsbjb.class);

                List<Wmlsb> wmlsbList = NetUtils.post6(NetConfig.getServerUrl(),
                        Wmlsb.toQuerySql(deskStatus.getWmdbh()), Wmlsb.class);

                if (wmlsbjbList.size() > 0) {
                    getDb().wmlsbjbDao().deleteAll();
                    getDb().wmlsbjbDao().insert(wmlsbjbList.get(0));

                    getDb().wmlsbDao().deleteAll();
                    if (wmlsbList.size() > 0) {
                        getDb().wmlsbDao().insert(wmlsbList);

                        OrderList.getInstance().handleWmlsb();
                        OrderList.getInstance().performRefresh();
                    }

                    //
                    createDccz(wmlsbjbList.get(0).getZh());

                    mHandler.post(() -> {
                        mOnGotoListener.onGotoOrderFragment();
                    });
                }

            } catch (IOException e) {
                Log.e(TAG, "queryServerOrder: ", e);
                mHandler.post(() -> {
                    Toast.makeText(getContext(), "服务器查询错误", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    @Override
    public void onCateItemClick(DeskGroup deskGroup) {
        mItemAdapter.setList(deskGroup.getDeskList());
    }

    @Override
    public void onDeskItemClick(Desk desk) {
        if (getFragmentManager() == null) {
            return;
        }

        if (desk.getDeskStatusList().size() > 1) {
            // 拼桌
            MergeTableDialogFragment fragment = MergeTableDialogFragment
                    .newInstance((ArrayList<? extends Parcelable>) desk.getDeskStatusList());
            fragment.show(getFragmentManager(), null);
            fragment.setOnItemClickListener(this::oneItemClick);

        } else if (desk.getDeskStatusList().size() == 1) {
            // 一个
            oneItemClick(desk.getDeskStatusList().get(0));

        } else if (desk.getDeskStatusList().size() == 0) {
            // 零个
            OpenTableDialogFragment fragment = new OpenTableDialogFragment();
            fragment.show(getFragmentManager(), null);
            fragment.setOnConfirmClickListener((gklx, peopleNum) -> {
                createDesk(desk.getJycssz(), gklx, peopleNum);
            });
        }
    }

    @SuppressWarnings("ConstantConditions")
    private void oneItemClick(DeskStatus deskStatus) {
        if (deskStatus.getDcczYhbh() != null) {
            // 有人在点单中
            if (Objects.equals(Settings.DEFAULT_YHJBQK.getYhbh(), deskStatus.getDcczYhbh())) {
                // 同一个用户放行
                InputDialogFragment fragment = InputDialogFragment.newInstanceInputPassword();
                fragment.setOkBtnClickListener(text -> {
                    if (getString(R.string.password).equals(text)) {

                        queryServerOrder(deskStatus);

                    } else {
                        Toast.makeText(getContext(), "密码错误", Toast.LENGTH_SHORT).show();
                    }
                });
                fragment.show(getFragmentManager(), null);

            } else {
                // 不同用户
                PromptDialogFragment fragment = PromptDialogFragment.newInstance(
                        deskStatus.getDcczYhmc() + "正在对该餐桌进行点餐\n" +
                                "您不能进入该餐桌进行点餐", true);
                fragment.show(getFragmentManager(), null);
            }

        } else {
            InputDialogFragment fragment = InputDialogFragment.newInstanceInputPassword();
            fragment.setOkBtnClickListener(text -> {
                if (getString(R.string.password).equals(text)) {

                    queryServerOrder(deskStatus);

                } else {
                    Toast.makeText(getContext(), "密码错误", Toast.LENGTH_SHORT).show();
                }
            });
            fragment.show(getFragmentManager(), null);
        }
    }

    private void createDccz(String deskName) {
        Dccz dccz = new Dccz();
        dccz.setZh(deskName);
        dccz.setYhmc(Settings.DEFAULT_YHJBQK.getYhmc());
        dccz.setBy1(Settings.DEFAULT_YHJBQK.getYhbh());
        dccz.setBy2(Settings.DEVICE_NAME);
        dccz.setBy5(new LocalDateTime());

        getDb().dcczDao().deleteAll();
        getDb().dcczDao().insert(dccz);
    }

    private OnGotoListener mOnGotoListener;

    public void setOnGotoListener(OnGotoListener onGotoListener) {
        mOnGotoListener = onGotoListener;
    }

    public interface OnGotoListener {
        void onGotoOrderFragment();

        void onGotoMenuFragment();
    }
}
